package admin.data;

import java.util.ArrayList;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import models.EmailModel;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class EmailData {
	
	private Objectify ofy;

	private Cache cache = null;

	private String prefix = "email_";

	private int limit = 20;

	private int page = 1;
	
	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public EmailData() {
		try {
			ObjectifyService.register(EmailModel.class);
		} catch (Exception e) {
			// e.printStackTrace();
		}

		try {
			cache = CacheManager.getInstance().getCacheFactory()
					.createCache(Collections.emptyMap());
		} catch (CacheException e) {
			// e.printStackTrace();
		}

		ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public ArrayList<EmailModel> list() {
		ArrayList<EmailModel> emails = new ArrayList<EmailModel>();

		int start = (page - 1) * limit;
		Query<EmailModel> q = ofy.query(EmailModel.class).limit(limit)
				.offset(start);
		for (EmailModel email : q) {
			emails.add(email);
		}

		return emails;
	}

	public ArrayList<EmailModel> getAll() {
		ArrayList<EmailModel> emails = new ArrayList<EmailModel>();

		Query<EmailModel> q = ofy.query(EmailModel.class);
		for (EmailModel email : q) {
			emails.add(email);
		}

		return emails;
	}
	
	public ArrayList<EmailModel> getByCity(String city) {
		ArrayList<EmailModel> emails = new ArrayList<EmailModel>();

		Query<EmailModel> q = ofy.query(EmailModel.class).filter("city", city);
		for (EmailModel email : q) {
			emails.add(email);
		}

		return emails;
	}

	public EmailModel getEmail(String id) {
		EmailModel email = new EmailModel();
		if (cache != null && cache.containsKey(id)) {
			email = (EmailModel) cache.get(id);
		} else {
			try {
				email = ofy.get(new Key<EmailModel>(EmailModel.class, id));
				cache.put(prefix + id, email);
			} catch (Exception e) {
				email = null;
			}
		}
		return email;
	}
	
	@SuppressWarnings("unchecked")
	public void insert(EmailModel email) {
		if (cache != null) {
			cache.put(prefix + email.getEmail(), email);
		}
		ofy.put(email);
	}

	public void delete(EmailModel email) {
		if (cache != null && cache.containsKey(prefix + email.getEmail())) {
			cache.remove(prefix + email.getEmail());
		}

		ofy.delete(email);
	}
}
